<script setup>
import { ref } from "vue";
import "@material/web/ripple/ripple";
import "@material/web/textfield/outlined-text-field.js";
import DatePickerPanel from "./docked/DatePickerPanel.vue";

const props = defineProps(["label", "placeholder", "required"]);
const model = defineModel();
const panelOpened = ref(false);
const input = ref(null);
const bottom = ref(false);

function mouseDown(event) {
  const pageHeight = document.body.clientHeight;
  const top = event.screenY;
  bottom.value = top < (pageHeight / 2);
  panelOpened.value = !panelOpened.value;
  input.value.focus();
}
</script>

<template>
  <div class="date-picker-docked">
    <DatePickerPanel tabindex="-1" class="date-picker-panel" :class="{ top: !bottom, bottom: bottom }" v-model="model"
      @submit="panelOpened = false" @cancel="panelOpened = false" :open="panelOpened">
    </DatePickerPanel>
    <md-outlined-text-field ref="input" @mousedown.prevent="mouseDown" :label="label" type="text"
      :placeholder="placeholder" supporting-text="YYYY-MM-DD" v-model="model">
      <div class="trailing-icon" slot="trailing-icon">
        <md-icon>calendar_today</md-icon>
        <md-ripple></md-ripple>
      </div>
    </md-outlined-text-field>
    <div @click="panelOpened = false" class="scrim" v-if="panelOpened"></div>
  </div>
</template>

<style scoped>
.date-picker-docked {
  position: relative;
}

.date-picker-panel {
  z-index: 1000;
}

.date-picker-panel.top {
  bottom: calc(100% + 16px);
}

.date-picker-panel.bottom {
  top: 100%;
}

md-outlined-text-field {
  --md-outlined-text-field-caret-color: transparent;
  --md-outlined-text-field-focus-caret-color: transparent;
  --md-outlined-text-field-error-caret-color: transparent;
}

.trailing-icon {
  position: relative;
  height: 36px;
  width: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 18px;
  --md-icon-size: 24px;
}

md-outlined-text-field::selection {
  background: inherit;
  color: inherit;
}

.scrim {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  background-color: transparent;
}
</style>